package org.mcjug;

import org.mcjug.model.StatusData;
import org.mcjug.model.StatusProvider;
import org.mcjug.model.UpdateIntentService;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.RemoteViews;

public class YambaWidget extends AppWidgetProvider {
	private static final String TAG = YambaWidget.class.getSimpleName();

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		Log.d(TAG, "onUpdated start");
		Cursor c = context.getContentResolver().query(
				StatusProvider.CONTENT_URI, null, null, null,
				StatusData.C_CREATED_AT + " DESC");
		try {
			if (c.moveToFirst()) {
				Log.d(TAG, "Results found in cursor ");
				CharSequence user = c.getString(c
						.getColumnIndex(StatusData.C_USER));
				CharSequence text = c.getString(c
						.getColumnIndex(StatusData.C_TEXT));
				CharSequence createdAt = DateUtils.getRelativeTimeSpanString(
						context,
						c.getLong(c.getColumnIndex(StatusData.C_CREATED_AT)));
				for (int id : appWidgetIds) {
					Log.d(TAG, "Updating widget " + id);
					RemoteViews rv = new RemoteViews(context.getPackageName(),
							R.layout.yamba_widget);
					rv.setTextViewText(R.id.rowUserTv, user);
					rv.setTextViewText(R.id.rowDateTv, createdAt);
					rv.setTextViewText(R.id.rowTextTv, text);
					Log.d(TAG, "Done Updating widget " + id);
					appWidgetManager.updateAppWidget(id, rv);
				}
			} else {
				Log.d(TAG, "No data to update");
			}
		} finally {
			c.close();
		}
		Log.d(TAG, "onUpdated end");
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d(TAG, "Recieved intent: " + intent.getAction());
		if (intent.getAction()
				.equals(UpdateIntentService.BROADCAST_INTENT_NAME)
				|| intent.getAction().equals(
						"android.appwidget.action.APPWIDGET_UPDATE")) {
			Log.d(TAG, "Gonna update the widget");
			AppWidgetManager appWidgetManager = AppWidgetManager
					.getInstance(context);
			onUpdate(context, appWidgetManager,
					appWidgetManager.getAppWidgetIds(new ComponentName(context,
							YambaWidget.class)));
			Log.d(TAG, "Done updating the widget");
		}
	}

}
